package com.zhongmai.yzfgrabanorder.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.zhongmai.yzfgrabanorder.R;
import com.zhongmai.yzfgrabanorder.base.BaseActivity;
import com.zhongmai.yzfgrabanorder.base.MyApplication;
import com.zhongmai.yzfgrabanorder.fragment.GrabAnOrderFragment;
import com.zhongmai.yzfgrabanorder.fragment.OrderFragment;
import com.zhongmai.yzfgrabanorder.fragment.PersonalFragment;
import com.zhongmai.yzfgrabanorder.utils.Constants;
import com.zhongmai.yzfgrabanorder.utils.EncryptUtils;
import com.zhongmai.yzfgrabanorder.utils.HttpXUtils;
import com.zhongmai.yzfgrabanorder.utils.LogUtils;
import com.zhongmai.yzfgrabanorder.utils.LogcatFileManager;
import com.zhongmai.yzfgrabanorder.utils.MD5Util;
import com.zhongmai.yzfgrabanorder.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.RequestParams;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;

import butterknife.BindView;

/**
 * 项目名称：YZFGrabAnOrder
 * 类描述：主页Activity
 * 创建人：Administrator
 * 创建时间：2020/9/11 16:57
 * 修改人：Administrator
 * 修改时间：2020/9/11 16:57
 * 修改备注：
 */
public class MainActivity extends BaseActivity {
    @BindView(R.id.mTV_title)
    TextView mTV_title;
    @BindView(R.id.mVP)
    ViewPager mVP;
    @BindView(R.id.mTL)
    SlidingTabLayout mTL;
    private static String[] permissions = {
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.INTERNET,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private ArrayList<Fragment> mFragments;

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void initView() {
        setStatusBar();
        mFragments = new ArrayList<>();
        mFragments.add(new GrabAnOrderFragment());
        mFragments.add(new OrderFragment());
        mFragments.add(new PersonalFragment());
        //无需编写适配器，一行代码关联TabLayout与ViewPager
        mTL.setViewPager(mVP, new String[]{"首页", "订单", "个人"}, this, mFragments);
        //mTL.setIndicatorHeight(5);
        mTL.setIndicatorWidth(115);
        mTL.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                switch (position) {
                    case 2:
                        mTV_title.setText("个人中心");
                        break;
                }
            }

            @Override
            public void onTabReselect(int position) {
            }
        });
    }

    @Override
    protected void initData() {
        requestPermission();
        String phoneMark = Utils.getPhoneMark();
        if (TextUtils.isEmpty(phoneMark)) {
            showToast("无法获取设备信息...");
            return;
        } else if (phoneMark.contains("null")) {
            return;
        } else {
            phoneMark = phoneMark.replaceAll(" ", "").trim();
            logMag("user---------" + phoneMark);
            Constants.user = MD5Util.MD5_16(phoneMark);
        }
    }

    /**
     * 请求权限
     */
    public void requestPermission() {
        int agreedCount = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            for (String permission : permissions) {
                int i = ContextCompat.checkSelfPermission(this, permission);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                logMag("checkSelfPermission = " + permission + "------status-------" + i);
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有授予该权限，就去提示用户请求
                    ActivityCompat.requestPermissions(MainActivity.this, permissions, 321);
                } else {
                    agreedCount++;
                }
            }
            logMag("-------------------agreedCount----------------=" + agreedCount);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //        super.onActivityResult(requestCode, resultCode, data);
        logMag("requestCode======" + requestCode + "------------" + resultCode);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    logMag("刷新");
                    OrderFragment fragment = (OrderFragment) mFragments.get(1);
                    fragment.refreshList();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 提示用户该请求权限的弹出框
     */
    private void showDialogTipUserRequestPermission() {
        AlertDialog.Builder dialogTipUserRequestPermissionBuilder = new AlertDialog.Builder(this)
                .setTitle("读取短信权限不可用")
                .setMessage("由于app要获取短信内容；\n否则，您将无法正常使用app")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false);
        if (dialogTipUserRequestPermissionBuilder != null) {
            dialogTipUserRequestPermissionBuilder.show();
        }
    }

    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        showToast("权限失败，请在-应用设置-权限-中，允许app使用存储权限来保存用户数据，获取手机信息");
                    } else
                        finish();
                } else {
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * 显示订单标签小红点
     */
    public void slidingTabLayoutRedDotShow(){
        mTL.showDot(1);
    }
    /**
     * 隐藏订单标签小红点
     */
    public void slidingTabLayoutRedDotGone (){
        mTL.hideMsg(1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogcatFileManager.getInstance().stopLogcatManager();
    }
}
